﻿using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;


namespace MsExchangeBcsConnector.ExchangeBdcModel.Helpers
{

    class SearchServiceApplicationUtils
    {


        internal static BusinessDataContentSource GetContentSourceByName(string name)
        {
            foreach (SearchServiceApplication searchApp in SearchService.Service.SearchApplications) //SearchServiceApplications
            {
                Content content = new Content(searchApp);

                foreach (ContentSource cs in content.ContentSources)
                {
                    BusinessDataContentSource cccs = cs as BusinessDataContentSource;
                    if (cccs != null)
                    {
                        if (cccs.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
                            return cccs;
                    }
                }
            }

            return null;
        }


        internal static void WaitForFullOrIncrementalCrawl(string contentSourceName)
        {
            var contentSource = GetContentSourceByName(contentSourceName);
            var crawlStatus = contentSource.CrawlStatus;

            int retryCount = 60;

            while (crawlStatus != CrawlStatus.CrawlingFull && crawlStatus != CrawlStatus.CrawlingIncremental)
            {
                System.Threading.Thread.Sleep(1000);

                contentSource = GetContentSourceByName(contentSourceName);
                crawlStatus = contentSource.CrawlStatus;

                if (retryCount == 1)
                    break;

                retryCount--;
            }
        }


    }
}
